import { defineStore } from 'pinia'
import { login, getUserInfo } from '@/api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    userId: localStorage.getItem('userId') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || '{}')
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.userId,
    userRole: (state) => state.userInfo?.roleId || ''
  },
  
  actions: {
    // 登录
    async login(userInfo) {
      try {
        const response = await login(userInfo)
        const { data } = response
        
        if (data) {
          this.userId = data.id
          this.userInfo = data
          
          // 保存到本地存储
          localStorage.setItem('userId', data.id)
          localStorage.setItem('userInfo', JSON.stringify(data))
        }
        
        return response
      } catch (error) {
        console.error('登录失败:', error)
        throw error
      }
    },
    
    // 获取用户信息
    async getUserInfo(id) {
      try {
        const response = await getUserInfo(id)
        const { data } = response
        
        if (data) {
          this.userInfo = data
          localStorage.setItem('userInfo', JSON.stringify(data))
        }
        
        return response
      } catch (error) {
        console.error('获取用户信息失败:', error)
        throw error
      }
    },
    
    // 退出登录
    logout() {
      this.userId = ''
      this.userInfo = {}
      
      // 清除本地存储
      localStorage.removeItem('userId')
      localStorage.removeItem('userInfo')
    }
  }
}) 